<?php
namespace app\mobile\controller;

use think\Db;
use think\Url;
use think\Cache;
use think\Request;
use think\Session;
use app\mobile\model\Ad;
use app\mobile\model\Shop;
use app\mobile\model\Config;
use app\mobile\model\Coupon;
use app\mobile\model\Member;
use app\mobile\model\QuotHour;
use app\mobile\model\GoodsType;
use app\mobile\model\ShopGoods;
use app\mobile\model\Promotion;
use app\mobile\model\MemberSign;
use app\mobile\model\LimitedType;
use app\mobile\model\MemberCoupon;
use app\mobile\model\MemberBrowse;
use think\Log;
use app\interfaces\model\Config as ConfigModel;

/**
 * Class UserPort
 * @package app\mobile\controller    用户端登录等
 */
class UserPort extends BaseController
{

    // 前置方法
    protected $beforeActionList = [
        'checkLogin'  => ['only' => 'login'],
        'checkMember' => ['only' => 'sign_in,get_ticket']
    ];

    /*
     * 用户登录
     */
    // public function login()
    // {
    //
    //     if (Request::instance()->isPost()) {
    //         $result = (new Member())->login_auth();
    //         return $result;
    //     }
    //
    //     //是否含有推荐人id  Request::instance()->domain()
    //     $redirect_uri = urlencode("http://www.hillyzx.com/index.php/mobile/third_party/wechat_login.html");
    //     if (Request::instance()->has('uid', 'get')) {
    //         $invit_id = Request::instance()->get('uid');
    //         $redirect_uri = urlencode("http://www.hillyzx.com/index.php/mobile/third_party/wechat_login?invit_id=" . $invit_id);
    //     }
    //
    //     //微信登录(wap公众平台)
    //     $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx00d16084747d84af&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect&wechat_redirect";
    //     return $this->fetch('', [
    //         'wx_url' => $url,
    //     ]);
    // }


    public function login()
    {

        if (Request::instance()->isPost()) {
            $result = (new Member())->login_auth2();
            $param = Request::instance()->param();
            halt($param);
            //return $result;
        }
        // 判断
        $action = array_key_exists('remember', $_COOKIE);
        if ($action) {
            $action = 1;
        } else {
            $action = 2;
        }

        $user = "";
        $tt = "";
        if ($action == 1) {
            $tt = $_COOKIE['remember'];
            $nn = Db::name('member_a')->where('member_name', $tt)->value('key');
            $arr = explode(',', $nn);
            $user = $arr[0];
        }

        $to_url = Request::instance()->domain()."/index.php/mobile/third_party/wechat_login.html";

        $redirect_uri = urlencode($to_url);
        if (Request::instance()->has('uid', 'get')) {
            $invit_id = Request::instance()->get('uid');
            $int_url = Request::instance()->domain()."/index.php/mobile/third_party/wechat_login?invit_id=". $invit_id;
            $redirect_uri = urlencode($int_url);
        }
        \config('app');
        //微信登录(wap公众平台)
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8b29fa71bc1aa7ea&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect&wechat_redirect";
        //return view('user');

        return $this->fetch('', [
            'wx_url' => $url,
            'user'   => $user,
            'mm'     => $action,

        ]);
        //
    }

    /*
     * 用户注册
     */
    public function register(Request $request)
    {

        if ($request->isPost()) {
            $data = $request->post();

            if (!Cache::has('reg_code')) {
                return ['code' => 0, 'message' => '验证码已失效,请重新获取'];
            }
            $code = Cache::get('reg_code');
            if ($code == $data['yzm']) {
                $model = new Member();
                $arr = $model->where('username', $data['username'])->find();
                if ($arr) {
                    return ['code' => 0, 'message' => '此账户已存在'];
                }
                if (count(explode(' ', $data['password'])) > 1) {
                    return ['code' => 401, 'message' => '密码含空格'];
                }
                //执行注册
                $res = (new Member())->reg();

                if ($res) {
                    //生成一张专属二维码
                   // (new ScanCode())->qrcodeWithPicture($res);
                }
               // Session::set('member_id', $res);  //生成全局会员id
                return ['code' => 200, 'message' => '注册成功'];
            } else {
                return ['code' => 0, 'message' => '验证码不正确'];
            }
        }
    }

    public function send(){
        (new \app\index\controller\Coupon())->send(1,2969);
    }

    /**
     * @param Request $request
     * @param $manage_id
     * @return array|mixed|\think\response\View
     * 业务员邀请会员
     */
    public function share_member(Request $request, $manage_id = 1)
    {
        if ($request->isPost()) {
            try {
                if (!Cache::has('reg_code')) {
                    return ['code' => 0, 'message' => '验证码已失效,请重新获取'];
                }
                if($manage_id == 17){
                    $manage_id = 1;
                }
                if($manage_id == 0){
                    $manage_id = 1;
                }

                $username = Request::instance()->param('username');
                $password = Request::instance()->param('password');
                $yzm = Request::instance()->param('yzm');
                if (Cache::get('reg_code') != $yzm) {
                    return ['code' => 0, 'message' => '验证码错误'];
                }
                $member = Db::name('member')->where('username', $username)->find();
                if ($member) return ['code' => 400, 'message' => '会员已注册过'];
                $member_id = Db::name('member')->insertGetId(['salesman_id' => $manage_id,'username' => $username, 'password' => sha1($password),'create_time' => date('Y-m-d H:i:s',time())]);
                (new \app\index\controller\Coupon())->send(2,$member_id);
                //if ($member) return ['code' => 400, 'message' => '会员信息不正确'];
                $share_member = Db::name('share_member')->where('member_id', $member_id)->where('manage_id', $manage_id)->find();
                if ($share_member) return ['code' => 400, 'message' => '会员已邀请过'];
                $ret = Db::name('share_member')->insert(['member_id' => $member_id, 'manage_id' => $manage_id, 'username' => $username, 'create_time' => date('Y-m-d H:i:s', time())]);
                if ($ret) {
                    return ['code' => 200, 'message' => '会员邀请成功'];
                }
            } catch (\Exception $e) {
                return ['code' => 0, 'message' => $e->getMessage()];
            }

        }
        return view('user_port_member', []);
    }

    /**
     * @param Request $request
     * @param $manage_id
     * @return array|mixed|\think\response\View
     *  门店邀请会员
     */
    public function shop_member(Request $request, $shop_id)
    {
        if ($request->isPost()) {
            try {
                if (!Cache::has('reg_code')) {
                    return ['code' => 0, 'message' => '验证码已失效,请重新获取'];
                }
                $username = Request::instance()->param('username');
                $password = Request::instance()->param('password');
                $yzm = Request::instance()->param('yzm');
                if (Cache::get('reg_code') != $yzm) {
                    return ['code' => 0, 'message' => '验证码错误'];
                }
                $member = Db::name('member')->where('username', $username)->find();
                if ($member) return ['code' => 400, 'message' => '会员已注册过'];
                $member_id = Db::name('member')->insertGetId(['username' => $username, 'password' => sha1($password),'shop_invite_id' => $shop_id,'create_time' => date('Y-m-d H:i:s',time())]);
                (new \app\index\controller\Coupon())->send(2,$member_id);
                //if ($member) return ['code' => 400, 'message' => '会员信息不正确'];

                if ($member_id) {
                    return ['code' => 200, 'message' => '门店邀请会员成功'];
                }
            } catch (\Exception $e) {
                return ['code' => 0, 'message' => $e->getMessage()];
            }

        }
        return view('user_port_member', []);
    }

    /*
     * 找回密码
     */
    public function find_pwd(Request $request)
    {
        $member = new Member();
        if ($request->isPost() && $request->isAjax()) {
            if ($request->post('act') == 'detection') {  //验证手机号的存在性
                $arr = $member->where('username', $request->post('tel'))->find();
                return $arr ?: ['code' => 0, 'message' => '手机号码未注册!'];
            }
            //校验验证码
            if ($request->post('act') == 'nextStep') {
                $data = $request->post();

                if (!Cache::has('user_yzm')) {
                    return ['code' => 0, 'message' => '验证码已过期,请重新获取'];
                };
                if ($data['yzm'] != Cache::get('user_yzm')) {
                    return ['code' => 0, 'message' => '验证码不正确'];
                } else {
                    Session::set('username_edit', $data['username']);
                    return ['code' => 200, 'message' => '验证通过'];
                }
            }
        }
        return $this->fetch('');
    }

    /*
     * 获取验证码(找回密码)
     */
    public function getVerif(Request $request)
    {
        if ($request->isPost()) {
            $tel = $request->param('tel');
            $code = mt_rand(100000, 999999);  //验证码随机数
            //发送验证码
            $content = '您好,您的短信验证码为：' . $code;
            $result = sendSMS($tel, $content);

            if ($result > 0) {   //会员找回密码验证码
                Log::record('测试日志信息，这是警告级别','notice');
                Cache::set('user_yzm', $code, 300);

                return ['code' => 200, 'message' => '已发送'];
            }
            return ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
    }

    /*
     * 重置密码
     */
    public function reset_pwd(Request $request)
    {
        $username = Session::get('username_edit');
        if ($request->isPost()) {
            $data = $request->post('');

            //修改密码
            $member = new Member();
            $result = $member->validate('member.editPwd')
                ->isUpdate(true)
                ->allowField(true)
                ->where('username', $data['username'])
                ->update(['password' => md5(md5($data['password']))]);
            return $result || $result === 0 ? ['code' => 200, 'message' => '修改成功'] : ['code' => 0, 'message' => $member->getError()];
        }


        return $this->fetch('', [
            'username' => $username,
        ]);
    }

    /*
     * (用户端)首页
     */
    public function index()
    {

        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

        //轮播列表
        $banner_list = (new Ad)->where(['parenTid' => '20'])->field('linkUrl,picUrl,skip_type')->select();

        //促销商品
        $hotSpot = (new Promotion())->where('status', 1)->order(['sort' => 'desc', 'create_time' => 'desc'])
            ->field('id,title')->select();

        //限时抢购
        $quot_hour_model = new QuotHour();
        $hour = date('H');
        $ini['end_time'] = ['gt', $hour];
        $quot_id = $quot_hour_model->where($ini)->field('id,name,start_time,end_time')->find();
        $limit = Db::view('rush_hour', 'rush_id,goods_id,price,number,purchase_number,create_time')
            ->view('shop_goods', 'id,title,thumb_img,price as old_price', 'shop_goods.id = rush_hour.goods_id')
            ->where('rush_id', $quot_id['id'])
            ->order(['create_time' => 'desc'])->limit(10)->select();

        $end_time = $beginToday + ($quot_id['end_time'] * 3600);

        // $limit = Db::view('limited', 'parenTid,goods_id,price,number,purchase_number,status,create_time')
        //     ->view('limited_type', 'end_time', 'limited_type.id = limited.parenTid')
        //     ->view('shop_goods', 'id,title,thumb_img,rebate_percentage,price as old_price', 'shop_goods.id = limited.goods_id')
        //     ->where(['status' => '1', 'end_time' => ['gt', time()]])->order(['create_time' => 'asc'])->limit(4)->select();
        // $limitedType = new LimitedType();
        // $end_time = $limitedType->where('id', 2)->value('end_time');
        // $start_time = $limitedType->where('id', 2)->value('start_time');


        // 热点专题
        $hot_spot = (new Promotion())->field('id,title')->limit(4)->order('create_time', 'desc')->where('status',1)->select();

        // 首页热门市场
        $hot_list = GoodsType::where(['parenTid' => '0', 'index_recommend' => '1', 'status' => '1'])
            ->field('id,title,picUrl')->order(['sort' => 'desc'])->limit(2)->select();

        // 热门市场正常推荐
        $type_list = GoodsType::where(['parenTid' => '0', 'hot_recommend' => '1', 'status' => '1'])
            ->field('id,title,picUrl')->order(['sort' => 'desc'])->limit(4)->select();

        //猜你喜欢
        $guess_like = self::guess_like();

        // 发现好店
        $find_shops = (new Shop())->relation('ShopIndex')->where(['status' => '1', 'valid_time' => [['gt', time()], ['eq', ''], 'or'], 'index_recommend' => '1'])
            ->field('member_id,title,m_banner banner,member_id,index_recommend,type')->order(['sort' => 'desc'])->limit(3)->select();

        // 首页开关
        // 首页开关
        $config_arr = (new ConfigModel())->where('varname','in','web_special_price,web_hot_selling,web_brand_street,web_hot_market')->field('varname,varvalue')->select();
        $config = array_reduce($config_arr,function(&$config,$v){
            $config[$v['varname']] = $v['varvalue'];
            return $config;
        });
        $config_pic = (new ConfigModel())->where('varname','in','web_special_price1,web_hot_selling1,web_brand_street1')->field('varname,varvalue')->select();
        $config_pic1 = [];
        foreach ($config_pic as $k => &$v){
            $config_pic1[$v['varname']] = Request::instance()->domain().'/uploads/home_page/'.$v['varvalue'];
        }

        //分享sdk参数
        $sign = (new WxConfig())->sdk_config(Request::instance()->url(true));
        $sign = '';

        return $this->fetch('', [
            'jsSign'      => $sign,
            'limit'       => $limit,
            'config'      => $config,
            'config_pic'       => $config_pic1,
            'hot_spot'    => $hot_spot,
            'end_time'    => $end_time,
            'hotSpot'     => $hotSpot,
            'guess'       => $guess_like,
            'banner_list' => $banner_list,
            'type_list'   => $type_list,
            'hot_list'    => $hot_list,
            'quot_id'     => $quot_id['id'],
            'find_shop'   => $find_shops,

        ]);
    }


    public function guess_like()
    {
        // 实例化
        $shopGoods = new ShopGoods;
        $memberBrowse = new MemberBrowse;
        $guess_like = [];

        //猜你喜欢
        $map['state'] = 1;
        $map['status'] = 1;
        $map['activity'] = 2;
        // 开启推送
        if (Cache::get('web_related') == 'Y') {

            $map['related'] = ['eq', 1];
            $guess_like = $shopGoods->where($map)->field('id,title,price,thumb_img thumb_img,sale_number,rebate_percentage')->limit('10')->order(['rand()' => 'desc', 'create_time' => 'desc'])->select();
        } else {
            // 未开启推送且未登录
            if (empty(Session::has('member_id'))) {

                $guess_like = $shopGoods->where($map)->field('id,title,price,thumb_img,sale_number,rebate_percentage')->limit('10')->order(['rand()' => 'desc', 'create_time' => 'desc'])->select();
            } else {
                // 未开启推送且登录

                $brose = $memberBrowse->where('member_id', Session::get('member_id'))->field('goods_type')->order('create_time', 'desc')->limit(5)->select();
                // 如果浏览记录为空
                if (empty($brose)) {

                    $guess_like = $shopGoods->where($map)->field('id,title,price,thumb_img,sale_number,rebate_percentage')->limit('10')->order(['rand()' => 'desc', 'create_time' => 'desc'])->select();
                } else {
                    $new = [];
                    foreach ($brose as $value) {
                        $new[] = $value['goods_type'];
                    }

                    $brose_str = implode(',', $new);

                    $map['goods_id'] = ['in', $brose_str];

                    $guess_like = $shopGoods->where($map)->field('id,title,price,thumb_img,sale_number,rebate_percentage')->limit('10')->order(['rand()' => 'desc', 'create_time' => 'desc'])->select();

                }
            }
        }

        return $guess_like;
    }


    /*
     * 签到领积分
     */
    public function sign_in(Request $request)
    {
        $sign = new MemberSign();
        $integral = 0;
        if (Session::has('member_id')) {   //会员登录状态
            $member_id = Session::get('member_id');
            //查看会员积分
            $integral = (int)Member::where(['id' => $member_id])->value('integral');
        }
        //每日签到赠送的积分数
        $web_sign = (new MemberSign)->where(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d', time())])->value('sign');

        if (empty($web_sign)) {
            $web_sign = "";
        } else {
            $web_sign = "+" . $web_sign;
        }

        //获取积分日期
        if ($request->isPost() && $request->post('act') == 'getSign') {
            if (Session::has('member_id')) {
                return $sign->getSign(Session::get('member_id'));
            }
            return [];
        }
        //执行签到
        if ($request->isPost() && $request->post('act') == 'signing') {
            if (!Session::has('member_id')) {
                return ['code' => 404, 'message' => '请登录'];
            }
            //查看会员今日是否签到过
            $is_sign = $sign->where(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d')])->find();
            if ($is_sign) {
                return ['code' => 0, 'message' => '今天已经签到过了,请明天再来'];
            } else {
                // 启动事务
                Db::startTrans();
                try {
                    // 昨天是否签到 签到获得积分
                    $ini = [
                        'member_id' => Session::get('member_id'),
                        'sign_time' => date("Y-m-d", strtotime("-1 day")),
                    ];
                    $find = Db::name('member_sign')->where($ini)->find();

                    if (empty($find)) {
                        $sign_pre = 1;
                        // 添加记录
                        Db::name('member_sign')->insert(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d'), 'sign' => $sign_pre]);
                        // 增加积分
                        Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $sign_pre);
                        //增加获取积分记录
                        Db::name('integralRecord')->insert(['member_id' => Session::get('member_id'), 'type_id' => 1, 'type' => '签到', 'integral' => $sign_pre, 'title' => '签到', 'create_time' => time()]);
                    } else {
                        if ($find['sign'] == 64) {
                            $sign_pre = 1;
                            // 添加记录
                            Db::name('member_sign')->insert(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d'), 'sign' => $sign_pre]);
                            // 增加积分
                            Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $sign_pre);
                            //增加获取积分记录
                            Db::name('integralRecord')->insert(['member_id' => Session::get('member_id'), 'type_id' => 1, 'type' => '签到', 'integral' => $sign_pre, 'title' => '签到', 'create_time' => time()]);
                        } else {
                            if ($find['sign'] == 0) {
                                $find['sign'] = 0.5;
                            }
                            $sign_pre = $find['sign'] * 2;

                            // 添加记录
                            Db::name('member_sign')->insert(['member_id' => Session::get('member_id'), 'sign_time' => date('Y-m-d'), 'sign' => $sign_pre]);
                            // 增加积分
                            Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $sign_pre);
                            //增加获取积分记录
                            Db::name('integralRecord')->insert(['member_id' => Session::get('member_id'), 'type_id' => 1, 'type' => '签到', 'integral' => $sign_pre, 'title' => '签到', 'create_time' => time()]);
                        }
                    }
                    // 提交事务
                    Db::commit();
                    return ['code' => 200, 'message' => '签到成功,请明天再来', 'sign_pre' => $sign_pre];
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ['code' => 0, 'message' => '网络繁忙'];
                }
            }
        }
        return $this->fetch('', [
            'integral' => $integral,
            'web_sign' => $web_sign,
        ]);
    }

    /*
     * 惠赚钱
     */
    public function privilege_gain()
    {
        $item = Db::name('information')->where('parenTid', 48)->find();
        return $this->fetch('', [
            'item' => $item
        ]);
    }

    /*
     * 周周币
     */
    public function week_money()
    {
        return $this->fetch('');
    }

    /*
     * 热点(促销商品)
     */
    public function hot_spot(Request $request)
    {
        $model = new Promotion();

        if ($request->isPost()) {
            $page = $request->post('page', 1);

            $result['data'] = $model->where(['status' => '1'])->field('id,title,content,goods_id,picUrl,create_time')
                ->order(['sort' => 'desc', 'create_time' => 'desc'])->limit(($page - 1) * 5, 5)->select();

            $result['pages'] = ceil(count($result['data']) / 5);

            foreach ($result['data'] as $key => &$value) {
                $value['goods'] = (new ShopGoods)->where(['id' => ['in', $value['goods_id']]])->field('id,thumb_img')->select();
            }


            return $result;
        }
        return $this->fetch();
    }

    /*
     * 热点(促销商品)详情
     */
    public function hot_spot_details($action_id)
    {
        $model = new Promotion();
        $result = $model->where(['status' => '1'])->where('id', $action_id)->field('id,title,content,goods_id,picUrl,create_time')->find();

        $result['goods'] = ShopGoods::where(['id' => ['in', $result['goods_id']]])->field('id,thumb_img,title')->limit(3)->select();

        //分享sdk参数
        $sign = (new WxConfig())->sdk_config(Request::instance()->url(true));

        return $this->fetch('', [
            'jsSign'      => $sign,
            'result' => $result,
        ]);
    }

    /*
     * 限时抢购
     */
    // public function limit_go(Request $request)
    // {
    //     //距离本场结束时间  查找当前开通并且有效的限时抢购活动
    //     $end_time = (new LimitedType)->where(['status' => 1, 'end_time' => ['gt', time()]])->value('end_time');
    //     if ($request->isPost()) {
    //         $page = $request->post('page');
    //         $result['data'] = Db::view('limited', 'parenTid,goods_id,price,number,purchase_number,status,create_time')
    //             ->view('limited_type', 'end_time', 'limited_type.id = limited.parenTid')
    //             ->view('shop_goods', 'id,title,thumb_img,describe,rebate_percentage,price as old_price', 'shop_goods.id = limited.goods_id')
    //             ->where(['status' => '1', 'end_time' => ['gt', time()]])
    //             ->order(['create_time' => 'desc'])
    //             ->limit(($page - 1) * 10, 10)
    //             ->select();
    //         // 闭包
    //         $data['data'] = array_map(function ($dispose) {
    //             if (is_array($dispose)) {
    //                 foreach ($dispose as &$item) {
    //                     $item['current_time'] = time();
    //
    //                 }
    //             }
    //             return $dispose;
    //         }, $result);
    //         $result['pages'] = ceil(Db::view('limited', 'parenTid,goods_id,price,number,purchase_number,status,create_time')
    //                 ->view('limited_type', 'end_time', 'limited_type.id = limited.parenTid')
    //                 ->view('shop_goods', 'id,title,thumb_img,describe,rebate_percentage', 'shop_goods.id = limited.goods_id')
    //                 ->where(['status' => '1', 'end_time' => ['gt', time()]])
    //                 ->count() / 10);
    //         return $result;
    //     }
    //
    //
    //     return $this->fetch('', [
    //         'end_time' => $end_time,
    //     ]);
    // }
    public function limit_go(Request $request)
    {
        // 实例化
        $quot_hour_model = new QuotHour();
        $hour = date('H');
        $ini['end_time'] = ['gt', $hour];
        $type = $quot_hour_model->where($ini)->field('id,name,start_time,end_time')->limit(5)->select();
        $type_total = count($type);

        if ($type_total<5){
            $difference = 5-$type_total;
            $difference_type = $quot_hour_model->field('id,name,start_time,end_time')->limit($difference)->select();
            $type = array_merge($type,$difference_type);
        }

        if ($request->isPost()) {
            // 获取数据
            $type_id = Request::instance()->param('type_id');
            // 获取页码
            $page = $request->post('page');
            $result['data'] = Db::view('rush_hour', 'rush_id,goods_id,price,number,purchase_number,create_time')
                ->view('shop_goods', 'id,title,thumb_img,price as goods_price', 'shop_goods.id = rush_hour.goods_id')
                ->where('rush_id', 'like', '%,' . $type_id . ',%')->order(['create_time' => 'desc'])->limit(($page - 1) * 10, 10)->select();


            foreach ($result['data'] as &$value) {
                $value['prent'] = ceil($value['purchase_number']/$value['number'])*100;
            }



            $result['page'] = ceil(Db::view('rush_hour', 'rush_d,goods_id,price,number,purchase_number,create_time')
                ->view('shop_goods', 'id,title,thumb_img,price as goods_price,describe,rebate_percentage', 'shop_goods.id = rush_hour.goods_id')
                ->where('rush_id', 'like', '%,' . $type_id . ',%')->count() / 10);

            return $result;
        }


        return $this->fetch('',[
            'type' => $type,
        ]);
    }


    /*
     * 平台优惠券列表
     */
    public function get_ticket(Request $request, $id = -1)
    {
        //平台分类
        $cateList =GoodsType::where(['status' => '1'])->field('id,parenTid,title')->select();

        if ($request->isPost()) {
            // 实例化
            $model = new Coupon();
            //页码
            $page = $request->post('page', 1);
            //平台分类id查找
            $condition = ($request->post('id', -1) == -1) ? [] : ['parenTid' => $request->post('id')];

            //平台优惠券 已上架 未过期
            $result['data'] = $model->where(['member_id' => 0, 'status' => '1', 'end_time' => ['gt', time()]])->where($condition)
                ->field('id,title,actual_price,virtual_price,number,content,start_time,end_time,sort as receive_status')
                ->with(['memberCoupon' => function ($e) {

                    //查找会员优惠券,检测是否已领取
                    $e->where('member_id', Session::get('member_id'))->field('id,coupon_id,status,member_id');

                }])->order(['sort' => 'desc'])->limit(($page - 1) * 5, 5)->select();

            //总页数
            $result['pages'] = ceil($model->where(['member_id' => 0, 'status' => '1', 'end_time' => ['gt', time()]])->count('id') / 5);

            return $result;
        }
        return $this->fetch('', [

            'id'   => $id,
            'type' => recursion_node($cateList),
        ]);
    }


    /**
     * 领取平台优惠券
     */
    public function ticket_act()
    {
        if (Request::instance()->isPost()) {
            $id = Request::instance()->post('id');
            if (!Session::has('member_id')) {
                return ['code' => '404', 'message' => '请登录'];
            }
            $model = new Coupon();
            $info = $model->where('id', $id)->find();
            //检测优惠券库存
            if (!$info['number']) {
                return ['code' => 400, 'message' => '数量为空,无法领取'];
            }
            $opt = $info->getData();
            $opt['shop_id'] = 0;
            $opt['coupon_id'] = $opt['id'];
            $opt['member_id'] = Session::get('member_id');
            $opt['status'] = 2;
            $opt['create_time'] = time();

            unset($opt['id']);
            // 启动事务
            Db::startTrans();

            try {
                // 添加用户优惠券
                (new MemberCoupon())->allowField(true)->isUpdate(false)->save($opt);

                // 店铺优惠券自减一
                Db::name('coupon')->where('id', $id)->setDec('number');

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '领取成功'];

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 0, 'message' => '领取失败'];
            }
        }
    }


    public function error_shop()
    {

        return $this->fetch('');
    }

    /*
     * 检测用户是否登录
     */
    protected function checkLogin()
    {
        if (true === Session::has('member_id')) {
            $this->redirect(Url::build('user_info/my_shop_index'));
        }
    }


    protected function checkMember()
    {
        if (false === Session::has('member_id')) {
            $this->redirect(Url::build('user_port/login'));
        }
    }

}